<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
    <title>Cesium Satellite Visualization</title>
    <script src="https://cesium.com/downloads/cesiumjs/releases/1.98/Build/Cesium/Cesium.js"></script>
    <link href="https://cesium.com/downloads/cesiumjs/releases/1.98/Build/Cesium/Widgets/widgets.css" rel="stylesheet">
    <style>
        body, html {
            margin: 0;
            padding: 0;
            height: 100%;
            font-family: sans-serif;
        }

        #cesiumContainer {
            width: 100%;
            height: 100%;
        }

        #loading {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 10px 20px;
            background: rgba(255, 255, 255, 0.9);
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            z-index: 999;
        }

        #errorMsg {
            position: fixed;
            top: 20px;
            left: 20px;
            background: rgba(255, 0, 0, 0.8);
            color: white;
            padding: 10px 20px;
            border-radius: 5px;
            display: none;
            z-index: 999;
        }

        #visibilityInfo {
            position: fixed;
            bottom: 20px;
            left: 20px;
            background: rgba(255, 255, 255, 0.9);
            padding: 10px 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            display: none;
            z-index: 999;
        }

        #exportButton {
            position: fixed;
            top: 20px;
            left: 20px;
            background: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            z-index: 999;
            font-size: 14px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
        }

        #exportButton:hover {
            background: #45a049;
        }
    </style>
</head>

<body>
<button id="exportButton">导出 CZML</button>
<div id="cesiumContainer"></div>
<div id="loading">数据加载中...</div>
<div id="errorMsg">数据加载失败，请检查网络或后端</div>
<div id="visibilityInfo">卫星当前 <span id="visibilityStatus">不可见</span></div>

<script>
    // 全局变量存储 CZML 数据
    let czmlData;

    // 初始化 Cesium
    Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIzMzQ5NjU2ZC04ZjI0LTQwMjUtODgyYy0wZDEzODA4NGJjMzMiLCJpZCI6Mjg0NzE0LCJpYXQiOjE3NDIxMjQwNDF9.3u5rYEN8O8pVt4z6NF-hbruan4hhahPTsGldRPz2aSw';
    const viewer = new Cesium.Viewer('cesiumContainer', {
        timeline: true,
        animation: true,
        shouldAnimate: true
    });

    // 加载 CZML 数据
    document.addEventListener('DOMContentLoaded', () => {
        document.getElementById('loading').style.display = 'block';
        fetch('/j2000-orbit-czml2')
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                czmlData = data; // 存储到全局变量

                // 从 CZML 数据中获取地面站信息
                const groundStation = data.find(item => item.id === 'guangzhou-ground-station');
                if (groundStation) {
                    const { latitude, longitude, altitude } = groundStation;

                    // 调整相机视角
                    viewer.camera.setView({
                        destination: Cesium.Cartesian3.fromDegrees(longitude, latitude, 10000000),
                        orientation: {
                            heading: Cesium.Math.toRadians(0),
                            pitch: Cesium.Math.toRadians(-90),
                            roll: 0
                        }
                    });

                    // 添加地面站实体
                    viewer.entities.add({
                        position: Cesium.Cartesian3.fromDegrees(longitude, latitude, altitude),
                        point: {
                            pixelSize: 10,
                            color: Cesium.Color.YELLOW
                        },
                        label: {
                            text: '广州地面站',
                            font: '14px sans-serif',
                            fillColor: Cesium.Color.WHITE,
                            backgroundColor: Cesium.Color.BLACK.withAlpha(0.7),
                            padding: new Cesium.Cartesian2(7, 5),
                            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                            outlineWidth: 2,
                            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                            pixelOffset: new Cesium.Cartesian2(0, -10)
                        }
                    });
                }

                // 加载 CZML 数据源
                return Cesium.CzmlDataSource.load(data, {
                    referenceFrame: Cesium.ReferenceFrame.INERTIAL
                });
            })
            .then(dataSource => {
                viewer.dataSources.add(dataSource);
                document.getElementById('loading').style.display = 'none';
                viewer.zoomTo(dataSource);
                viewer.clock.shouldAnimate = true;

                // 处理卫星可见性信息
                const satelliteCzml = czmlData.find(item => item.id === 'j2000-satellite-1');
                if (satelliteCzml && satelliteCzml.show && satelliteCzml.show.intervals) {
                    const visibilityInfo = document.getElementById('visibilityInfo');
                    const visibilityStatus = document.getElementById('visibilityStatus');

                    viewer.clock.onTick.addEventListener(() => {
                        const currentTime = viewer.clock.currentTime;
                        const isVisible = satelliteCzml.show.intervals.some(interval => {
                            const [start, end] = interval.interval.split('/');
                            return Cesium.JulianDate.greaterThanOrEquals(currentTime, Cesium.JulianDate.fromIso8601(start)) &&
                                Cesium.JulianDate.lessThanOrEquals(currentTime, Cesium.JulianDate.fromIso8601(end)) &&
                                interval.boolean;
                        });

                        visibilityStatus.textContent = isVisible ? '可见' : '不可见';
                        visibilityInfo.style.display = 'block';
                    });
                }
            })
            .catch(error => {
                console.error('加载失败:', error);
                document.getElementById('loading').style.display = 'none';
                document.getElementById('errorMsg').style.display = 'block';
            });
    });

    /*document.getElementById('exportButton').addEventListener('click', function () {
        const json = JSON.stringify(czmlData, null, 2);
        fetch('/exportCzml', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: json
        })
            .then(response => response.blob())
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download ='satellite_orbit.czml';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
            })
            .catch(error => console.error('导出失败:', error));
    });*/

    document.getElementById('exportButton').addEventListener('click', function () {
        const json = JSON.stringify(czmlData, null, 2);
        fetch('/api/files/exportCzml', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: json
        })
            .then(response => response.blob())
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download ='satellite_orbit.czml';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);

                setTimeout(() => {
                    const userConfirm = confirm('文件已下载，请在下载对话框中查看保存路径，是否告知服务器保存路径？');
                    if (userConfirm) {
                        const path = prompt('请在下载对话框中查看路径后输入保存路径', '');
                        if (path) {
                            fetch('/savePath', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({ path: path })
                            })
                                .then(response => response.json())
                                .then(data => {
                                    console.log(data.message);
                                })
                                .catch(error => {
                                    console.error('发送路径失败', error);
                                });
                        }
                    }
                }, 1000); // 延迟 1 秒弹出提示，给下载操作一些时间
            })
            .catch(error => console.error('导出失败:', error));
    });


    // 清理资源
    window.addEventListener('beforeunload', () => {
        if (viewer && !viewer.isDestroyed()) {
            viewer.destroy();
        }
    });
</script>
</body>
</html>
